import Vue from 'vue'
import Vuex from 'vuex'
import { importFiles } from '@/utils/importFiles'
import { fetchCityList, fetchUserSetting } from '@/api/user'

Vue.use(Vuex)

const DEFAULT_MPA_CENTER = [104.07, 30.67]

export default new Vuex.Store({
  state: {
    mapCenter: DEFAULT_MPA_CENTER,
    userSetting: {
      isLogin: false
    }
  },
  mutations: {
    SET_MAP_CENTER(state, center = DEFAULT_MPA_CENTER) {
      state.mapCenter = center
    },
    SET_USER_SETTING(state, data) {
      state.userSetting = {
        ...state.userSetting,
        ...data
      }
    }
  },
  getters: {
    mapCenter: state => {
      return state.mapCenter
    },
    userSetting: state => {
      return state.userSetting
    }
  },
  actions: {
    changeMapCenter(ctx, center = DEFAULT_MPA_CENTER) {
      ctx.commit('SET_MAP_CENTER', center)
    },
    async loadCityList(ctx, params) {
      const _ret = await fetchCityList(params)
      return _ret
    },
    async loadUserSetting(ctx, data) {
      const { code, date } = await fetchUserSetting(data)
      if (code === 200) {
        const { lng, lat } = date
        ctx.commit('SET_MAP_CENTER', [lng, lat])
        ctx.commit('SET_USER_SETTING', {
          ...date,
          isLogin: true
        })
      }
    }
  },
  modules: {
    ...importFiles(require.context('./module', false, /\.js$/))
  }
})
